package Threads.extra;

//打印左右括号
//jyy的课上的例子

import javafx.beans.binding.ObjectExpression;

public class brackets {
    public static int N=5;
    public static volatile int count=0;
    public static void main(String[] args) {
        Object monitor=new Object();
        Thread p1=new Producer(monitor);
        Thread p2=new Producer(monitor);
        Thread c=new Consumer(monitor);
        p1.start();
        p2.start();
        c.start();
    }
    public static class Producer extends Thread {
        private Object o;

        public Producer(Object o) {
            this.o = o;
        }

        @Override
        public void run() {
            while (true) {
                synchronized (o) {
                    while (count == N) {
                        try {
                            o.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                    System.out.println("(");
                    count++;
                    o.notifyAll();
                }
            }
        }
    }
    public static class Consumer extends Thread{
        private Object o;

        public Consumer(Object o){
            this.o=o;
        }

        @Override
        public void run() {
            while (true) {
                synchronized (o) {
                    while (count == 0) {
                        try {
                            o.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                    System.out.println(")");
                    count--;
                    o.notifyAll();
                }
            }
        }
    }
}
